<template>
  <div class='main'>
    <a-form
      id='formLogin'
      class='user-layout-login'
      ref='formLogin'
      :form='form'
      :hideRequiredMark='true'
      @submit='handleSubmit'
    >
      <h5 class='title'>
<!--        {{ customActiveKey === 0 ? '登录' : '重置密码' }}-->
        <img v-if='customActiveKey === 0' src='@/assets/img/login/login_title.png' style='width: 244px;height: 45px'>
        <img v-if='customActiveKey === 1' src='@/assets/img/login/reset_title.png' style='width: 244px;height: 45px'>
      </h5>
      <a-form-item v-if='customActiveKey === 0'>
        <span slot='label'>
          <a-icon slot='prefix' type='user' :style="{ color: '#788998', marginRight: '3px', fontSize: '20px' }" />
          <span>账号</span>
        </span>
        <a-input
          size='large'
          type='text'
          placeholder='请输入账号'
          v-decorator="[
            'username',
            {
              rules: [{ required: true, message: '请输入账号' }, { validator: handleUsername }],
              initialValue:  'ruyonggang',
              validateTrigger: 'change'
            }
          ]"
        >
        </a-input>
      </a-form-item>

      <a-form-item v-if='customActiveKey === 1'>
        <span slot='label'>
          <a-icon type='phone' slot='prefix' :style="{ color: '#788998', marginRight: '3px', fontSize: '20px' }" />
          <span>手机号</span>
        </span>
        <a-input
          size='large'
          placeholder='请输入手机号'
          v-decorator="[
            'phone',
            {rules: [{ required: true, message: '请输入手机号' }, { pattern: phonePattern,  message: '请输入合法电话'}], validateTrigger: 'blur'}
          ]"
        >
        </a-input>
      </a-form-item>

      <a-form-item>
        <span slot='label'>
          <a-icon slot='prefix' type='lock' :style="{ color: '#788998', marginRight: '3px', fontSize: '20px' }" />
          <span>密码</span>
        </span>
        <a-input-password
          size='large'
          placeholder='请输入密码'
          v-decorator="[
            'password',
            {
              rules: [{ required: true, message: '请输入密码' }, { min: 4,  message: '密码可输入长度未4-10位', max: 10 }],
              validateTrigger: 'blur',
              initialValue:  'ruyonggang',
            }
          ]"
        >
        </a-input-password>
      </a-form-item>

      <a-form-item v-if='customActiveKey === 1'>
        <span slot='label'>
          <a-icon slot='prefix' type='lock' :style="{ color: '#788998', marginRight: '3px', fontSize: '20px' }" />
          <span>确认密码</span>
        </span>
        <a-input-password
          size='large'
          placeholder='请确认密码'
          v-decorator="[
            'rePassword',
            {rules: [{ required: true, message: '请确认密码' }], validateTrigger: 'blur'}
          ]"
        >
        </a-input-password>
      </a-form-item>

      <a-form-item v-if='customActiveKey === 0'>
        <a-row style="margin-bottom: 10px">
          <div>
            <Vcode :show="isShow" @fail="onFail" @success="onSuccess" @close="onClose" />
          </div>
<!--          <a-button type="primary" @click="submit" ghost block :icon="computeVerifyBtnIcon"-->
<!--                    :style="computeVerifyBtnStyle">-->
<!--            {{ computeVerifyBtnText }}-->
<!--          </a-button>-->
        </a-row>
        <a-button
          size='large'
          type='primary'
          htmlType='submit'
          class='login-button'
          :loading='state.loginBtn'
          :disabled='state.loginBtn'
          style='background-color: #2C3B58;border-color: #2C3B58'
        >登录
        </a-button>
        <p class='forget-password' @click='customActiveKey = 1'>忘记密码</p>
      </a-form-item>

      <a-form-item v-if='customActiveKey === 1'>
        <a-row>
          <a-col :span='12'>
            <a-button
              size='large'
              type='primary'
              htmlType='submit'
              class='reset-password-button'
              :loading='state.loginBtn'
              :disabled='state.loginBtn'
              style='width: 100%;background-color: #2C3B58;border-color: #2C3B58'
            >提交
            </a-button>
          </a-col>
          <a-col :span='8' :offset='2'>
            <p class='go-to-login' @click='customActiveKey = 0'>使用已有账号登录</p>
          </a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { strPattern1, phonePattern } from '@/reges'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getCaptchaImage, resetPassword } from '@/api/login'
import Vcode from 'vue-puzzle-vcode'
import { WS_CONECTION } from '@/store/mutation-types'

export default {
  components: {
    Vcode
  },
  data() {
    return {
      phonePattern,
      captchaImageOption: {},
      customActiveKey: 0,
      verifySuccess: -1,
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isShow: false,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  computed: {
    computeVerifyBtnText() {
      if (this.verifySuccess === -1) {
        return '开始验证'
      }
      if (this.verifySuccess === 1) {
        return '验证通过'
      }
      if (this.verifySuccess === 0) {
        return '验证失败'
      }
    },
    computeVerifyBtnIcon() {
      if (this.verifySuccess === -1) {
        return 'safety-certificate'
      }
      if (this.verifySuccess === 1) {
        return 'check-circle'
      }
      if (this.verifySuccess === 0) {
        return 'close-circle'
      }
    },
    computeVerifyBtnStyle() {
      if (this.verifySuccess === -1) {
        return {}
      }
      if (this.verifySuccess === 1) {
        return {
          color: 'green',
          borderColor: 'green'
        }
      }
      if (this.verifySuccess === 0) {
        return {
          color: 'red',
          borderColor: 'red'
        }
      }
    }
  },
  created() {
    this.getCaptchaImage()
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    submit() {
      this.isShow = true
    },
    onSuccess(msg) {
      console.log(msg, 'msgmsg--onSuccess')
      this.isShow = false
      const loginParams = { ...this.form.getFieldsValue() }
      // TODO: 暂时不使用加密
      this.Login(loginParams)
        .then((res) => this.loginSuccess(res))
        .catch(err => this.requestFailed(err))
        .finally(() => {
          this.state.loginBtn = false
        })
    },
    onFail() {
      this.verifySuccess = 0
    },
    onClose() {
      this.isShow = false
    },
    handleUsername(rule, value, callback) {
      const { state } = this
      if (strPattern1.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    resetPasswordSuccess(values) {
      this.customActiveKey = 0
      this.$message.success('密码重置成功、请直接登录!')
    },
    async getCaptchaImage() {
      const result = await getCaptchaImage()
      this.captchaImageOption = result
    },
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 0 ? ['username', 'password', 'code'] : ['username', 'password', 'phone', 'rePassword']
      validateFields(validateFieldsKey, { force: true }, async (err, values) => {
        if (!err) {
          if (customActiveKey === 0) {
            this.isShow = true
          } else {
            // TODO: 暂时不使用加密
            const resetParams = { ...values }
            resetPassword(resetParams)
              .then(res => this.resetPasswordSuccess(res))
              .catch(err => this.requestFailed(err))
              .finally(() => {
                state.loginBtn = false
              })
          }
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    loginSuccess(res) {
      this.$router.push({ path: '/' })
      this.$store.dispatch(WS_CONECTION)
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: timeFix(),
          description: `${res.nickName}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed(err) {
      this.isLoginError = true
    }
  }
}
</script>

<style lang='less' scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .title {
    font-size: 32px;
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 600;
    color: #DFE5EB;
    line-height: 65px;
    text-align: center;
  }

  /deep/ .ant-form-item-label > label {
    color: #788998;
    font-size: 20px
  }

  /deep/ .ant-input.ant-input-lg {
    background-color: #EDF0F6;
    border-radius: 4px 4px 4px 4px;
    color: #7C879C;
    border-width: 0px;
  }

  /deep/ .ant-input-affix-wrapper .ant-input-suffix {
    color: #788998;
  }

  /deep/ .ant-input-password-icon:hover {
    color: #788998;
  }

  /deep/ .ant-form-item {
    margin-bottom: 30px;
  }

  .text-color {
    color: #788998;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
    box-sizing: border-box;
    border-radius: 4px 4px 4px 4px;
  }

  .forget-password {
    color: #2C3B58;
    text-align: center;
    padding: 12px 0px;
    cursor: pointer;
  }

  .go-to-login {
    color: #2C3B58;
    text-align: center;
    cursor: pointer;
  }
}
</style>
